package CURD.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.malty.MyBatisApplication;
import com.malty.entity.Employee;
import com.malty.service.EmployeeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

@SpringBootTest(classes = MyBatisApplication.class)
@RunWith(SpringRunner.class)
public class saveOrUpdate {
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    EmployeeService employeeService;

    @Test
    public void saveOrUpdate() {
        // 会先查询是主键id否存在记录，然后再选择是更新还是插入
        // 主键为null时，自动选择插入
        // 隐藏了byid的语义
        Employee employee = Employee.builder().lastName("maltysahne").age(10).email("fasfd@asdfzx.com").gender("男").build();
        employeeService.saveOrUpdate(employee);
        Employee employee1 = Employee.builder().lastName("saveOrUpdate").age(17).email("fasfd@asdfzx.com").gender("女").build();
        employeeService.saveOrUpdate(employee1);
    }

    @Test
    public void saveOrUpdateWrapper() {
        // 对Wrapper条件筛选出的记录进行更新
        Employee employee = Employee.builder().lastName("maltysahne").age(10).email("fasfd@asdfzx.com").build();
        employeeService.saveOrUpdate(employee, Wrappers.<Employee>lambdaQuery().eq(Employee::getGender, "女"));
    }

    @Test
    public void saveOrUpdateBatch() throws InterruptedException {
        // 根据Id对表进行更新或插入，若id字段为空，则自动插入
        List<Employee> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Thread.sleep(20);
            Employee employee = Employee.builder().lastName("maltysahne" + System.currentTimeMillis() % 100).age(10).email("fasfd@asdfzx.com").build();
            if (i % 2 == 0) {
                employee.setId(i);
            }
            list.add(employee);
        }
        employeeService.saveOrUpdateBatch(list);
    }

    @Test
    public void saveOrUpdateBatchWithSize() throws InterruptedException {
        // 根据batch size 每次批量操作batch size条数据
        List<Employee> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Thread.sleep(20);
            Employee employee = Employee.builder().lastName("maltysahneBatch" + System.currentTimeMillis() % 100).age(10).email("fasfd@asdfzx.com").build();
            if (i % 3 == 0) {
                employee.setId(i);
            }
            list.add(employee);
        }
        employeeService.saveOrUpdateBatch(list, 2);
    }
}
